package scau.zxck.utils;

import scau.zxck.entity.Connection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 * Created by chenyulin on 2016/11/29.
 */
public class DatabaseUtil {

    /**
     * 判断连接是否可用
     * @param conn
     * @return
     */
    public static boolean testConnection(Connection conn) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://" + conn.getHost() + ":" + conn.getPort() +"/";
            String userName = conn.getUserName();
            String password = conn.getPassword();
            DriverManager.getConnection(url, userName, password);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取连接中的所有数据库名
     * @param conn
     * @return
     * @throws SQLException
     */
    public static ArrayList<String> showDatabases(Connection conn) throws SQLException {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        ArrayList<String> databaseList = new ArrayList<String>();
        String host = conn.getHost();
        String userName = conn.getUserName();
        String password = conn.getPassword();
        String port = conn.getPort();
        java.sql.Connection connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port +"/", userName, password);
        Statement statement = connection.createStatement();
        String sql = "show databases";
        ResultSet rs = statement.executeQuery(sql);
        while (rs.next()) {
            databaseList.add(rs.getString(1));
        }
        return databaseList;
    }

}
